package com.atguigu.lease.web.admin.custom.converter;

import com.atguigu.lease.model.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

@Component
public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {
    //制造转换器方法
    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        //返回具体转换器方法
        return new Converter<String, T>() {
            //1. 获取枚举的全部值
            //ItemType.values(); //枚举的.values获取全部值
            //2. 循环获取枚举的getCode 和 source对象
            @Override
            public T convert(String source) {
                for (T enumConstant : targetType.getEnumConstants()) {
                    //3. 如何相同直接返回类型
                    if (enumConstant.getCode() == Integer.parseInt(source)){
                        return enumConstant;
                    }
                }
                //4、循环以后没有的话抛异常
                throw new RuntimeException("非法类型异常");
            }
        };
    }
}
